using System;
using System.Configuration;
using System.Xml;

namespace Common.Unity.Extensions.Configuration.Configuration
{
	class ObjectConfigurationElementCollection : ConfigurationElementCollection
	{
		protected override ConfigurationElement CreateNewElement()
		{
			throw new NotImplementedException();
		}

		protected override object GetElementKey( ConfigurationElement element )
		{
			return ( (ObjectConfigurationElement)element ).Name;
		}

		///<summary>
		/// Figure out the concrete type to create given the type attribute on the given
		/// xml reader. If not present, throws an exception.
		///</summary>
		///
		///<returns>
		///true if the unrecognized element was deserialized successfully; otherwise, false. The default is false.
		///</returns>
		///
		///<param name="reader">An input stream that reads XML from the configuration file. </param>
		///<param name="elementName">The name of the unrecognized element. </param>
		///<exception cref="T:System.ArgumentException">elementName starts with the reserved prefix "config" or "lock".</exception>
		///<exception cref="T:System.Configuration.ConfigurationErrorsException">The element specified in elementName is the &lt;clear&gt; element.</exception>
		protected override bool OnDeserializeUnrecognizedElement( string elementName, XmlReader reader )
		{
			if ( elementName == AddElementName )
			{
				string typeName = reader.GetAttribute( "type" );
				if( !string.IsNullOrEmpty( typeName ) )
				{
					Type elementType = Type.GetType(typeName);
					ObjectConfigurationElement element = (ObjectConfigurationElement)Activator.CreateInstance( elementType );
					element.DeserializeElement( reader );
					BaseAdd( element );
					return true;
				}
			}
			return base.OnDeserializeUnrecognizedElement(elementName, reader);
		}
	}
}